package com.scau.jansing.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;

/**
 * Created by jansing on 2015/10/9.
 */
public class FileUtils {

    /**
     * 将内容输出到本项目下指定类文件中，<br/>
     * 为避免覆盖原文件，输出到/create/原路径
     * @param content 输出内容
     * @param packageString 指定类路径
     * @return 文件路径
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static String outputToFile(String content, String packageString) throws IOException, ClassNotFoundException {

        StringBuilder temp = new StringBuilder();

        //定位到项目根路径
        String path = Class.class.getResource("/").getPath();
        File file = new File(path);
        File app = file.getParentFile().getParentFile();

        temp.append(app.getPath()).append("\\src");
        Iterator<File> fileIterator = Arrays.asList(app.listFiles()).iterator();
        //maven项目比普通项目多了/main/java
        while(fileIterator.hasNext()){
            file = fileIterator.next();
            if(file.getName().equals("pom.xml")){
                temp.append(CommonUtils.MAVEN_EXTRA_PATH);
                file = null;
                break;
            }
        }
        temp.append("\\").append(packageString.replaceAll("\\.", "\\\\")).append(".java");

        String realPath = temp.toString();
        File javaFile = new File(realPath);
        if(!javaFile.getParentFile().exists()){
            javaFile.getParentFile().mkdirs();
        }

        FileOutputStream output = new FileOutputStream(javaFile);
        output.write(content.getBytes());
        output.flush();
        output.close();
        return "Create the file in : " + realPath;
    }
}
